const express = require('express');
const WebSocket = require('ws');
const http = require('http');



// 作为服务器接受用户数据
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });


// 作为客户端给控制数据库后台发送数据
const wsData = new WebSocket('ws://localhost:8081');
 
let data = null
wsData.onopen = function() {
     console.log('链接成功');
  };
wsData.onmessage = function(event) {
    console.log(`接收数据: ${event.data}`);
    data = JSON.parse(event.data)
};
 wsData.onclose = function(event) {
            console.log('关闭');
        };

        wsData.onerror = function(error) {
            console.error('错误:', error);
        };
// ws.send('123')
// 添加promise写法
// function sendWithPromise(socket, data) {
//   return new Promise((resolve, reject) => {
//     socket.send(JSON.stringify(data), (error) => {
//       if (error) {
//         reject(error);
//       } else {
//         resolve('Data sent successfully');
//       }
//     });
//   });
// }

wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('Received data: %s', message);
        const data = JSON.parse(message);
        console.log(data);
        // Process the data as needed, e.g., store in a database
        wsData.send(JSON.stringify(data))
        // sendWithPromise(wsData, data).then(res => {
        //     wsData.onmessage = function(event) {
        //         console.log(`接收数据: ${event.data}`);
        //     };
            
        // })
    });
    ws.send(JSON.stringify(data))
    
    
});

server.listen(8080, () => {
    console.log('Server is running on http://localhost:8080');
});